package com.xinhe.web.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;

@Slf4j
public class FileUtil {

    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0L) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            toFile = inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    private static File inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }


    public static File getJarResourceFile(String filePath) {
        File file = null;
        try {
            int decimalPoint = filePath.lastIndexOf(".");
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            InputStream inputStream = classPathResource.getInputStream();
            file = File.createTempFile("file", (decimalPoint >= 0) ? filePath.substring(decimalPoint) : "");
            FileUtils.copyInputStreamToFile(inputStream, file);
        } catch (IOException e) {
            log.error("resource文件读取失败：{}", e.getMessage());
        }
        return file;
    }


    public static String downloadIcon(String iconUrl, String folder, String resourceHome) {
        String icon = "https://images.weserv.nl/?url=" + iconUrl;

        String fileName = String.format("%s_%d%s", new Object[]{folder, Long.valueOf(System.currentTimeMillis()), iconUrl.substring(iconUrl.lastIndexOf("."))});
        String upload = "/upload/";
        try {
            URL url = new URL(icon);
            DataInputStream dis = new DataInputStream(url.openStream());

            String imagesName = String.format("%s%s%s/%s", new Object[]{resourceHome, upload, folder, fileName});
            File file = new File(resourceHome + upload + folder);
            if (!file.exists()) {
                file.mkdirs();
            }

            FileOutputStream fos = new FileOutputStream(new File(imagesName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];

            int length;
            while ((length = dis.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fos.write(output.toByteArray());
            dis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return upload + folder + fileName;
    }


    public static boolean deleteFile(String filePath) {
        return deleteFile(new File(filePath));
    }


    public static boolean deleteFile(File file) {
        if (file == null || !file.exists()) {
            log.error("文件删除失败,请检查文件是否存在以及文件路径是否正确");
            return false;
        }

        File[] files = file.listFiles();

        if (files != null && files.length > 0) {
            for (File f : files) {

                if (f.isDirectory()) {

                    deleteFile(f);
                } else {

                    boolean bool = f.delete();
                    if (bool) {
                        log.debug("删除文件成功，文件名：{}", f.getName());
                    } else {
                        log.debug("删除文件失败，文件名：{}", f.getName());
                    }
                }
            }
        }

        boolean delete = file.delete();
        if (delete) {
            log.debug("删除（文件/文件夹）成功，（文件/文件夹）名：{}", file.getName());
        } else {
            log.debug("删除（文件/文件夹）失败，（文件/文件夹）名：{}", file.getName());
        }
        return true;
    }
}
